package 行为型模式


/**
 * 在不破坏封装性的前提下，捕获一个对象的内部状态，并在该对象之外保存这个状态
 */

class TextEditor2 {
    private val buffer = StringBuilder()
    fun add(ch: Char) {
        buffer.append(ch)
    }

    fun add(s: String?) {
        buffer.append(s)
    }

    fun delete() {
        if (buffer.isNotEmpty()) {
            buffer.deleteCharAt(buffer.length - 1)
        }
    }

    // 获取状态:
    fun getState(): String? {
        return buffer.toString()
    }

    // 恢复状态:
    fun setState(state: String?) {
        buffer.delete(0, buffer.length)
        buffer.append(state)
    }
}

// 备忘录类
class Memento(private val state: String) {
    fun getState(): String {
        return state
    }
}


// 发起人类
class TextEditor3(state: String) {
    private val buffer = StringBuilder()

    init {
        setState(state)
    }

    fun add(ch: Char) {
        buffer.append(ch)
    }

    fun add(s: String?) {
        buffer.append(s)
    }

    fun setState(state: String) {
        buffer.delete(0, buffer.length)
        buffer.append(state)
    }

    fun delete() {
        if (buffer.isNotEmpty()) {
            buffer.deleteCharAt(buffer.length - 1)
        }
    }

    fun save(): Memento {
        return Memento(buffer.toString())
    }

    fun restore(memento: Memento) {
        setState(memento.getState())
    }

    fun getState(): String {
        return buffer.toString()
    }
}

// 管理者类
class Caretaker {
    private val mementoList: MutableList<Memento> = mutableListOf()

    fun addMemento(memento: Memento) {
        mementoList.add(memento)
    }

    fun getMemento(index: Int): Memento {
        return mementoList[index]
    }
}


fun main(args: Array<String>) {
    val caretaker = Caretaker()
    val textEditor = TextEditor3("I love the world!")
    println(textEditor.getState())

    caretaker.addMemento(textEditor.save())
    textEditor.setState("I hate the world!")

    println(textEditor.getState())

    textEditor.restore(caretaker.getMemento(0))
    println(textEditor.getState())
}